package com.suos.core.logic;

import com.suos.conf.SuOsProperties;
import com.suos.core.entity.SysInfo;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 客户端连接重试机制
 *
 * @author : MisShi
 * @date: 2021-10-26 11:30:31
 */
@Slf4j
@NoArgsConstructor
public class ConnectionListener implements ChannelFutureListener {

    private SuOsProperties suOsProperties;

    private SysInfo sysInfo;


    public ConnectionListener(SuOsProperties suOsProperties, SysInfo sysInfo) {
        this.suOsProperties = suOsProperties;
        this.sysInfo = sysInfo;
    }

    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (!channelFuture.isSuccess()) {
            final EventLoop eventLoop = channelFuture.channel().eventLoop();
            eventLoop.schedule(() -> {
                try {
                    log.info(sysInfo.getUnbid() + "-->重试");
                    new SugarClient(suOsProperties, sysInfo).start();
                } catch (Exception e) {
                    log.warn("{}重试异常:{}", sysInfo.getUnbid(), e.getStackTrace()[0]);
                }
            }, suOsProperties.getReconInter(), TimeUnit.SECONDS);
        }
    }
}
